package com.wuming.house.controller;

import com.wuming.house.core.BusinessException;
import com.wuming.house.core.CommonResult;
import com.wuming.house.core.JsonResult;
import com.wuming.house.model.WeixinUser;
import com.wuming.house.service.WeixinUserService;
import com.wuming.house.util.DateUtil;
import com.yuanzhuo.common.core.excel.excelexport.ExportManager;
import com.yuanzhuo.common.core.excel.excelexport.bean.SheetBean;
import com.yuanzhuo.common.core.util.YzStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by hanfei on 16/4/19.
 */
@Controller
@RequestMapping("/web/user")
public class WexinUserController extends BaseController {

    @Autowired
    private WeixinUserService weixinUserService;


    @RequestMapping(value = "/toManageUser", method = RequestMethod.GET)
    public String toManageUser() {
        return "/user/manageUser";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult list(@RequestParam(required = false) String name, @RequestParam(required = false) String mobile, @RequestParam(defaultValue = "1") int pageIndex
            , @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<WeixinUser> users = weixinUserService.getWeixinUserByPage(name, mobile, pageIndex, pageSize);
            int total = weixinUserService.getTotal(name, mobile);
            return CommonResult.createSuccessResult(users, total, "查询当天用户总数成功.");
        } catch (BusinessException be) {
            logger.error("查询用户失败.异常:{}", be.getMessage());
            return CommonResult.createFailureResult("查询用户失败");
        } catch (Exception e) {
            logger.error("查询用户失败.异常:{}", e.getMessage());
            return CommonResult.createFailureResult("查询用户失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/count", method = RequestMethod.GET)
    public JsonResult count() {
        Date currentDate = DateUtil.nowTime();
        String startTime = DateUtil.dateToString(currentDate, "yyyy-MM-dd") + " 00:00:00";
        String endTime = DateUtil.dateToString(currentDate, "yyyy-MM-dd") + " 23:59:59";
        try {
            int total = weixinUserService.getTotalByTime(startTime, endTime);
            return new JsonResult(total, "查询当天用户总数成功.", true);
        } catch (BusinessException be) {
            logger.error("查询当天用户总数失败.异常:{}", be.getMessage());
            return new JsonResult(null, "查询当天用户总数成功.", false);
        } catch (Exception e) {
            logger.error("查询当天用户总数失败.异常:{}", e.getMessage());
            return new JsonResult(null, "查询当天用户总数成功.", false);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/export")
    public JsonResult export() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<WeixinUser> users = weixinUserService.getWeixinUserByPage("", "", 1, 9999);
            for (WeixinUser user : users) {
                String genderName = user.getGender() == 1 ? "男" : "女";
                user.setGenderName(genderName);
                user.setTime(DateUtil.dateToString(user.getCreateTime(), "yyyy-MM-dd"));
            }
            List<String> headerList = new ArrayList<String>();
            List<String> attributes = new ArrayList<String>();
            headerList.add("昵称");
            attributes.add("nickname");
            headerList.add("用户名");
            attributes.add("realname");
            headerList.add("省");
            attributes.add("province");
            headerList.add("市");
            attributes.add("city");
            headerList.add("性别");
            attributes.add("genderName");
            headerList.add("手机号");
            attributes.add("mobile");
            headerList.add("年龄");
            attributes.add("age");
            headerList.add("职业");
            attributes.add("profession");
            headerList.add("地址");
            attributes.add("userAddr");
            headerList.add("添加时间");
            attributes.add("time");
            String[] headers = (String[]) headerList.toArray(new String[headerList.size()]);
            String sysTemp = System.getProperty("java.io.tmpdir");
            String tempFileName = UUID.randomUUID().toString() + ".xls";
            File file = new File(sysTemp + File.separator + tempFileName);
            OutputStream out = new FileOutputStream(file);
            ExportManager.getInstance().exportJavaBeanData("用户列表", new SheetBean<WeixinUser>("用户列表", "人员列表", headers, users, attributes),
                    out);
            resultMap.put("filename", tempFileName);
            resultMap.put("showName", "用户列表.xls");
        } catch (Exception e) {
            logger.error("发生系统异常,异常信息:{}", e.getMessage());
            return new JsonResult<Object>(null, "导出失败", false);
        }
        return new JsonResult<Object>(resultMap, "导出成功", true);
    }

    @Override
    @RequestMapping("downLoadTempFile")
    public void downLoadTempFile(@RequestParam String filename, HttpServletRequest request,
                                 HttpServletResponse response, @RequestParam String showName) throws IOException {
        File backFileName = new File(System.getProperty("java.io.tmpdir") + File.separator + filename);
        if (backFileName.exists()) {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + YzStringUtils.toUtf8String(showName) + "\"");
            InputStream in;
            try {
                ServletOutputStream os = response.getOutputStream();
                in = new FileInputStream(backFileName);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);// 将文件写入服务器
                }
                os.close();
                in.close();
                backFileName.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
